package com.ruoyi.business.alarm.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.ruoyi.business.alarm.domain.DoorAlarmLog;

import jakarta.annotation.PostConstruct;

/**
 * 报警WebSocket服务
 * 用于推送报警信息到前端
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class AlarmWebSocketService {

    private static final Logger log = LoggerFactory.getLogger(AlarmWebSocketService.class);

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        log.info("报警WebSocket服务初始化完成，使用Spring WebSocket API");
    }

    /**
     * 发送报警通知
     * 当有新的报警产生时调用
     * 
     * @param alarmLog 报警日志对象
     */
    public void sendAlarmNotification(DoorAlarmLog alarmLog) {
        if (alarmLog == null) {
            log.warn("报警日志为空，无法发送WebSocket通知");
            return;
        }

        try {
            log.info("发送报警通知到WebSocket，报警ID: {}, 槽号: {}, 类型: {}, 当前连接数: {}", 
                alarmLog.getAlarmId(), 
                alarmLog.getSlotNumber(), 
                alarmLog.getAlarmType(),
                AlarmWebSocketHandler.getConnectionCount());
            
            // 发送报警消息
            AlarmWebSocketHandler.sendAlarm(alarmLog);
            
            log.info("报警通知已发送到WebSocket，报警ID: {}", alarmLog.getAlarmId());
        } catch (Exception e) {
            log.error("发送报警WebSocket通知失败，报警ID: {}", alarmLog.getAlarmId(), e);
        }
    }

    /**
     * 发送报警结束通知
     * 当报警结束时调用
     * 
     * @param alarmLog 报警日志对象
     */
    public void sendAlarmEnd(DoorAlarmLog alarmLog) {
        if (alarmLog == null) {
            return;
        }

        try {
            log.debug("发送报警结束通知到WebSocket，报警ID: {}, 槽号: {}", 
                alarmLog.getAlarmId(), 
                alarmLog.getSlotNumber());
            
            AlarmWebSocketHandler.sendAlarmEnd(alarmLog);
        } catch (Exception e) {
            log.error("发送报警结束WebSocket通知失败，报警ID: {}", alarmLog.getAlarmId(), e);
        }
    }

    /**
     * 获取当前WebSocket连接数
     */
    public int getConnectionCount() {
        return AlarmWebSocketHandler.getConnectionCount();
    }
}

